import logging
import base64
from openai import OpenAI
from django.conf import settings

logger = logging.getLogger(__name__)

class QwenAIHandler:
    def __init__(self, streaming=False):
        try:
            logger.info("初始化千问AI处理器")
            self.client = OpenAI(
                api_key=settings.QWEN_CONFIG['API_KEY'],
                base_url="https://dashscope.aliyuncs.com/compatible-mode/v1"
            )
            self.streaming = streaming
            logger.info("千问AI处理器初始化成功")
        except Exception as e:
            logger.error(f"千问AI处理器初始化失败: {str(e)}", exc_info=True)
            raise

    def generate_response(self, messages):
        try:
            logger.info("开始生成响应")
            logger.info(f"处理消息: {messages}")
            
            completion = self.client.chat.completions.create(
                model=settings.QWEN_CONFIG['MODEL'],
                messages=messages,
                modalities=["text"],
                stream=True,
                stream_options={"include_usage": True}
            )
            
            # 收集所有的响应片段
            response_text = ""
            for chunk in completion:
                if chunk.choices:
                    if chunk.choices[0].delta.content:
                        response_text += chunk.choices[0].delta.content
                else:
                    logger.info(f"Usage info: {chunk.usage}")
            
            logger.info(f"生成响应成功: {response_text}")
            return response_text
            
        except Exception as e:
            logger.error(f"生成响应失败: {str(e)}", exc_info=True)
            raise

    async def generate_stream_response(self, messages):
        try:
            logger.info("开始流式生成响应")
            completion = self.client.chat.completions.create(
                model=settings.QWEN_CONFIG['MODEL'],
                messages=messages,
                modalities=["text"],
                stream=True,
                stream_options={"include_usage": True}
            )
            
            async for chunk in completion:
                if chunk.choices:
                    if chunk.choices[0].delta.content:
                        yield chunk.choices[0].delta.content
                else:
                    logger.info(f"Usage info: {chunk.usage}")
                    
        except Exception as e:
            logger.error(f"流式生成响应失败: {str(e)}", exc_info=True)
            raise 